package com.yuexunit.operationman.nbsy.module.InterventionalOperation.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import com.yuexunit.operationman.nbsy.R;
import com.yuexunit.operationman.nbsy.base.BaseKJActivity;
import com.yuexunit.operationman.nbsy.base.ExitApplication;
import com.yuexunit.operationman.nbsy.base.SubmitBean;
import com.yuexunit.operationman.nbsy.config.AppConfig;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.Bean.DrugBean;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.adapter.DrugListAdapter;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.adapter.OtherListAdapter;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.model.impl.InterNurseModel;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.presenter.IInterNursePresenter;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.presenter.impl.InterNursePresenter;
import com.yuexunit.operationman.nbsy.module.InterventionalOperation.ui.view.IInterNurseView;
import com.yuexunit.operationman.nbsy.widget.CustomDatePicker;
import com.yuexunit.operationman.nbsy.widget.FixedSwipeListView;
import com.yuexunit.operationman.nbsy.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2017/7/24 0024.
 */

public class Act_InterventionalOperation_Infor extends BaseKJActivity implements IInterNurseView {
    @Bind(R.id.tv_patient_name)
    TextView tvPatientName;
    @Bind(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @Bind(R.id.tv_patient_visitno)
    TextView tvPatientVisitno;
    @Bind(R.id.tv_patient_disease)
    TextView tvPatientDisease;
    @Bind(R.id.postoperative_diagnosis)
    EditText postoperativeDiagnosis;
    @Bind(R.id.general_anesthesia)
    CheckBox generalAnesthesia;
    @Bind(R.id.local_anesthesia)
    CheckBox localAnesthesia;
    @Bind(R.id.surface_anesthesia)
    CheckBox surfaceAnesthesia;
    //    @Bind(R.id.anesthetics)
//    EditText anesthetics;
//    @Bind(R.id.dosage)
//    EditText dosage;
    @Bind(R.id.analgesia_listview)
    FixedSwipeListView analgesiaListview;
    @Bind(R.id.anesthesia)
    EditText anesthesia;
    @Bind(R.id.anesthesia_start)
    TextView anesthesiaStart;
    @Bind(R.id.anesthesia_end)
    TextView anesthesiaEnd;
    @Bind(R.id.operation_start)
    TextView operationStart;
    @Bind(R.id.operation_end)
    TextView operationEnd;
    @Bind(R.id.surgeon)
    EditText surgeon;
    @Bind(R.id.listview)
    FixedSwipeListView listview;
    @Bind(R.id.tour)
    EditText tour;

    LoadingDialog loadingDialog;
    IInterNursePresenter presenter;

    ArrayList<DrugBean> drugBeans = new ArrayList<>();
    ArrayList<DrugBean> OtherDrugBeans = new ArrayList<>();
    DrugListAdapter adapter;
    OtherListAdapter otherListAdapter;


    @Override
    public void setRootView() {
        setContentView(R.layout.act_interventionaloperation_infor);
        ButterKnife.bind(this);
        ExitApplication.getInstance().addActivity(this);
    }

    @Override
    public void initData() {
        super.initData();
        loadingDialog = new LoadingDialog(this);
        presenter = new InterNursePresenter(this, new InterNurseModel());
        setTitle();
        setContent();

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(aty, Act_InterventionalOperation_DrugList.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("drug", drugBeans.get(i));
                bundle.putInt("type", 2);
                bundle.putInt("position", i);
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
            }
        });

        analgesiaListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(aty, Act_InterventionalOperation_Other.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("drug", OtherDrugBeans.get(i));
                bundle.putInt("type", 2);
                bundle.putInt("position", i);
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
            }
        });
    }

    private void setTitle() {
        tvPatientName.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getPatientName());
        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getPatientSex().equals("1")) {
            tvPatientSex.setText("男");
        } else if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getPatientSex().equals("2")) {
            tvPatientSex.setText("女");
        } else {
            tvPatientSex.setText("不详");
        }
        tvPatientVisitno.setText("住院号" + AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getInHospitalNo());
        tvPatientDisease.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationName());
    }

    private void setContent() {
//        postoperativeDiagnosis.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationAfterDesc());
        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaType() != null) {
            if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaType().equals("1")) {
                generalAnesthesia.setChecked(true);
            } else if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaType().equals("2")) {
                localAnesthesia.setChecked(true);
            }
            else if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaType().equals("3")) {
                surfaceAnesthesia.setChecked(true);
            }
        }
//        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure() != null) {
//            if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure().length() > 0) {
//                anesthetics.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure().split(";", -1)[0]);
//                dosage.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure().split(";", -1)[1]);
//            }
//        }
        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure() != null
                && AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure().length() > 0) {
            String[] medicine = AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnaesthesiaMeasure().split(";", -1);

            for (int i = 0; i < medicine.length; i++) {
                DrugBean drugBean = new DrugBean();
                drugBean.setName(medicine[i]);
                OtherDrugBeans.add(drugBean);
            }

            otherListAdapter = new OtherListAdapter(analgesiaListview, OtherDrugBeans, R.layout.item_other_list);
            analgesiaListview.setAdapter(otherListAdapter);
        }

        anesthesia.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnestheSign());
        anesthesiaStart.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnesthesiaStartTimeStr());
        anesthesiaEnd.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getAnesthesiaEndTimeStr());
        operationStart.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationStartTimeStr());
        operationEnd.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationEndTimeStr());
        surgeon.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationDoctorSign());
        tour.setText(AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getCircuit());

        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationMedicine() != null
                && AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationMedicine().length() > 0
                && AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getInjectionTime() != null
                && AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getInjectionTime().length() > 0) {
            String[] medicine = AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getOperationMedicine().split(";", -1);
            String[] time = AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getInjectionTime().split(";", -1);

            for (int i = 0; i < medicine.length; i++) {
                DrugBean drugBean = new DrugBean();
                drugBean.setName(medicine[i]);
                drugBean.setStartTime(time[i].split("~", -1)[0]);
                drugBean.setEndTime(time[i].split("~", -1)[1]);
                drugBeans.add(drugBean);
            }

            adapter = new DrugListAdapter(listview, drugBeans, R.layout.item_drug_list);
            listview.setAdapter(adapter);
        }
    }

    @OnClick({R.id.titlebar_docadvice_img_back, R.id.general_anesthesia,
            R.id.local_anesthesia, R.id.surface_anesthesia, R.id.iv_anesthesia_start,
            R.id.iv_anesthesia_end, R.id.iv_operation_start,
            R.id.iv_operation_end, R.id.flax_meter, R.id.sure, R.id.bt_add_drug
            , R.id.bt_add_analgesia})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.titlebar_docadvice_img_back:
                finish();
                break;
            case R.id.general_anesthesia:
                if (localAnesthesia.isChecked()) {
                    localAnesthesia.setChecked(false);
                }
                if (surfaceAnesthesia.isChecked()) {
                    surfaceAnesthesia.setChecked(false);
                }
                break;
            case R.id.local_anesthesia:
                if (generalAnesthesia.isChecked()) {
                    generalAnesthesia.setChecked(false);
                }
                if (surfaceAnesthesia.isChecked()) {
                    surfaceAnesthesia.setChecked(false);
                }
                break;
            case R.id.surface_anesthesia:
                if (localAnesthesia.isChecked()) {
                    localAnesthesia.setChecked(false);
                }
                if (generalAnesthesia.isChecked()) {
                    generalAnesthesia.setChecked(false);
                }
                break;
            case R.id.iv_anesthesia_start:
                initDatePicker(anesthesiaStart);
                break;
            case R.id.iv_anesthesia_end:
                initDatePicker(anesthesiaEnd);
                break;
            case R.id.iv_operation_start:
                initDatePicker(operationStart);
                break;
            case R.id.iv_operation_end:
                initDatePicker(operationEnd);
                break;
            case R.id.flax_meter:
                startActivity(new Intent(aty, Act_InterventionalOperation_FlaxMeter.class));
                break;
            case R.id.sure:
                insertContent();
                break;
            case R.id.bt_add_drug:
                Intent intent = new Intent(this, Act_InterventionalOperation_DrugList.class);
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
                break;
            case R.id.bt_add_analgesia:
                Intent intent1 = new Intent(this, Act_InterventionalOperation_Other.class);
                Bundle bundle1 = new Bundle();
                bundle1.putInt("type", 1);
                intent1.putExtras(bundle1);
                aty.startActivityForResult(intent1, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                if (data.getExtras().getInt("position") == -1) {
                    DrugBean drug = (DrugBean) data.getExtras().getSerializable("drug");
                    drugBeans.add(drug);
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter = new DrugListAdapter(listview, drugBeans, R.layout.item_drug_list);
                        listview.setAdapter(adapter);
                    }
                } else {
                    DrugBean drug = (DrugBean) data.getExtras().getSerializable("drug");
                    drugBeans.set(data.getExtras().getInt("position"), drug);
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter = new DrugListAdapter(listview, drugBeans, R.layout.item_drug_list);
                        listview.setAdapter(adapter);
                    }
                }
                break;
            case 20000:
                if (data.getExtras().getInt("position") == -1) {
                    DrugBean drug = (DrugBean) data.getExtras().getSerializable("drug");
                    OtherDrugBeans.add(drug);
                    if (otherListAdapter != null) {
                        otherListAdapter.notifyDataSetChanged();
                    } else {
                        otherListAdapter = new OtherListAdapter(analgesiaListview, OtherDrugBeans, R.layout.item_other_list);
                        analgesiaListview.setAdapter(otherListAdapter);
                    }
                } else {
                    DrugBean drug = (DrugBean) data.getExtras().getSerializable("drug");
                    OtherDrugBeans.set(data.getExtras().getInt("position"), drug);
                    if (otherListAdapter != null) {
                        otherListAdapter.notifyDataSetChanged();
                    } else {
                        otherListAdapter = new OtherListAdapter(analgesiaListview, OtherDrugBeans, R.layout.item_other_list);
                        analgesiaListview.setAdapter(otherListAdapter);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void insertContent() {
//        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationAfterDesc(postoperativeDiagnosis.getText().toString());
        if (generalAnesthesia.isChecked()) {
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaType("1");
        }
        if (localAnesthesia.isChecked()) {
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaType("2");
        }
        if (surfaceAnesthesia.isChecked()) {
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaType("3");
        }
        if (OtherDrugBeans.size() > 0) {
            String medicine = "";
            for (int i = 0; i < OtherDrugBeans.size(); i++) {
                if (medicine.length() > 0) {
                    medicine += ";" + OtherDrugBeans.get(i).getName();
                } else {
                    medicine += OtherDrugBeans.get(i).getName();
                }
            }
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaMeasure(medicine);
        } else if (OtherDrugBeans.size() == 0) {
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaMeasure("");
        }

//        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnaesthesiaMeasure(anesthetics.getText().toString() + ";" + dosage.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnestheSign(anesthesia.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnesthesiaStartTimeStr(anesthesiaStart.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setAnesthesiaEndTimeStr(anesthesiaEnd.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationStartTimeStr(operationStart.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationEndTimeStr(operationEnd.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationDoctorSign(surgeon.getText().toString());
        AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setCircuit(tour.getText().toString());

        if (drugBeans.size() > 0) {
            String medicine = "", time = "";
            for (int i = 0; i < drugBeans.size(); i++) {
                if (medicine.length() > 0) {
                    medicine += ";" + drugBeans.get(i).getName();
                } else {
                    medicine += drugBeans.get(i).getName();
                }

                if (time.length() > 0) {
                    time += ";" + drugBeans.get(i).getStartTime() + "~" + drugBeans.get(i).getEndTime();
                } else {
                    time += drugBeans.get(i).getStartTime() + "~" + drugBeans.get(i).getEndTime();
                }
            }
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationMedicine(medicine);
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setInjectionTime(time);
        } else if (drugBeans.size() == 0) {
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setOperationMedicine("");
            AppConfig.INTERNURSEBEAN.getObject().getInterNursing().setInjectionTime("");
        }

        if (AppConfig.INTERNURSEBEAN.getObject().getInterNursing().getInterId() == null) {
            Map<String, String> params = new HashMap<>();
            params.put("operationNo", PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.INTERNURSEBEAN));
            presenter.insertInterNurseDate(params);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("accountId", PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.USER_ACCOUNT) + "");
            params.put("fullName", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_FULLNAME) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.INTERNURSEBEAN));
            presenter.updateInterNurseDate(params);
        }
    }

    private void initDatePicker(final TextView view) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date date1 = null;
        try {
            if (view.getText().toString().length() > 0) {
                date1 = sdf.parse(view.getText().toString());
            } else {
                date1 = new Date();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String now = sdf.format(date1);

        CustomDatePicker customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                view.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 循环滚动
        customDatePicker1.show(now);
    }


    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void insertInterNurseDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void updateInterNurseDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
